package com.leoren.run.activity.myself;

import android.app.ProgressDialog;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;

import com.leoren.run.R;
import com.leoren.run.common.ResponseCode;
import com.leoren.run.common.ServerResponse;
import com.leoren.run.common.UrlConstants;
import com.leoren.run.dbbean.UserDB;
import com.leoren.run.log.L;
import com.leoren.run.utils.GsonUtil;
import com.leoren.run.utils.Http.OkHttp.CommonOkHttpClient;
import com.leoren.run.utils.Http.OkHttp.exception.OkHttpException;
import com.leoren.run.utils.Http.OkHttp.listener.DisposeDataHandle;
import com.leoren.run.utils.Http.OkHttp.listener.DisposeDataListener;
import com.leoren.run.utils.Http.OkHttp.request.CommonRequest;
import com.leoren.run.utils.StringUtils;
import com.leoren.run.utils.ToastUtil;
import com.leoren.run.vo.User;

import org.litepal.LitePal;

import okhttp3.FormBody;
import okhttp3.Request;
import okhttp3.RequestBody;

/**
 * 更新用户密码界面
 */
public class UpdatePasswordActivity extends AppCompatActivity implements View.OnClickListener {

    private Toolbar toolbar;
    private EditText oldEdit;
    private EditText newEdit;
    private EditText reEdit;
    private Button finishBtn;

    private ProgressDialog progressDialog;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_update_password);

        initLayout();
    }

    private void initLayout(){
        toolbar = findViewById(R.id.update_password_toolbar);
        setSupportActionBar(toolbar);
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        toolbar.setNavigationOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                finish();
            }
        });

        oldEdit = findViewById(R.id.update_old_password_text);
        newEdit = findViewById(R.id.update_new_password_text);
        reEdit = findViewById(R.id.update_re_password_text);
        finishBtn = findViewById(R.id.finish_update_password_btn);
        finishBtn.setOnClickListener(this);
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()){
            case R.id.finish_update_password_btn:
                updatePassword();
                break;
            default:
                break;
        }
    }

    /**
     * 网络请求进行密码更新
     * @return
     */
    private int updatePassword(){
        String oldPassword = oldEdit.getText().toString().trim();
        String newPassword = newEdit.getText().toString().trim();
        final String rePassword = reEdit.getText().toString().trim();

        if(StringUtils.isBlank(oldPassword)){
            ToastUtil.MakeToast("旧密码不能为空");
            return 0;
        }else if(StringUtils.isBlank(newPassword)){
            ToastUtil.MakeToast("新密码不能为空");
            return 0;
        }else if(!newPassword.equals(rePassword)){
            ToastUtil.MakeToast("两次输入密码不一致");
            return 0;
        }
        final UserDB userDB = LitePal.findFirst(UserDB.class);
        if(userDB == null){
            ToastUtil.MakeToast("网络错误，请重新登陆后再试");
            return 0;
        }
        showProgressDialog();
        RequestBody body = new FormBody.Builder()
                .add("id", String.valueOf(userDB.getTagId()))
                .add("oldPassword", oldPassword)
                .add("newPassword", newPassword)
                .build();
        final Request request = CommonRequest.createPostRequest(UrlConstants.USER_UPDATE_PASSWORD, body);
        CommonOkHttpClient.post(request, new DisposeDataHandle(new DisposeDataListener() {
            @Override
            public void onSuccess(String responseStr) {
                closeProgressDialog();
                L.e("更改密码 ============" + responseStr);
                ServerResponse<User> response = GsonUtil.formatJsonToResponseUser(responseStr);
                if(response == null){
                    if(response == null){
                        onFailure(new OkHttpException(ResponseCode.NETWORK_ERROR.getCode(), ResponseCode.NETWORK_ERROR.getValue()));
                        return;
                    }
                    if(!response.isSuccess()){
                        onFailure(new OkHttpException(ResponseCode.UNKNOWN_ERROR.getCode(), response.getMsg()));
                        return;
                    }
                    if (response.getStatus() == ResponseCode.SUCCESS.getCode()) {
                        User user = response.getData();
                        userDB.setPassword(user.getPassword());
                        userDB.update(userDB.getTagId());
                    }
                    ToastUtil.MakeToast(response.getMsg());
                    UpdatePasswordActivity.this.finish();
                }
            }

            @Override
            public void onFailure(OkHttpException e) {
                closeProgressDialog();
                ToastUtil.MakeToast(e.getMsg() + "");
            }
        }));
        return 0;
    }


    /**
     * 显示进度对话框
     */
    private void showProgressDialog(){
        if(progressDialog == null){
            progressDialog = new ProgressDialog(this);
            progressDialog.setMessage("正在加载...");
            progressDialog.setCanceledOnTouchOutside(false);
        }
        progressDialog.show();
    }

    /**
     * 关闭进度对话框
     */
    private void closeProgressDialog(){
        if(progressDialog != null){
            progressDialog.dismiss();
        }
    }
}
